import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { prisma } from '@/lib/prisma';
import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';

export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const tripId = params.id;
    
    // 检查行程是否存在
    const trip = await prisma.trip.findUnique({
      where: { id: tripId },
    });

    if (!trip) {
      return NextResponse.json({ error: '行程不存在' }, { status: 404 });
    }

    // 检查是否已经收藏
    const existingSave = await prisma.savedTrip.findFirst({
      where: {
        userId: session.user.id,
        tripId: tripId,
      },
    });

    if (existingSave) {
      // 如果已经收藏，则取消收藏
      await prisma.savedTrip.delete({
        where: { id: existingSave.id },
      });
      return NextResponse.json({ saved: false });
    }

    // 如果未收藏，则添加收藏
    await prisma.savedTrip.create({
      data: {
        userId: session.user.id,
        tripId: tripId,
      },
    });

    // 重新验证相关页面
    revalidatePath('/popular-trips');
    revalidatePath('/profile');
    revalidatePath(`/trips/${tripId}`);

    return NextResponse.json({ saved: true });
  } catch (error) {
    console.error('Save trip error:', error);
    return NextResponse.json(
      { error: '收藏行程失败' },
      { status: 500 }
    );
  }
}

// 获取收藏状态
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ saved: false });
    }

    const savedTrip = await prisma.savedTrip.findUnique({
      where: {
        userId_tripId: {
          userId: session.user.id,
          tripId: params.id,
        },
      },
    });

    return NextResponse.json({ saved: !!savedTrip });
  } catch (error) {
    console.error('Get save status error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
} 